package com.yc.thread.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class TestReadAndWriteLock2 {

    public static void main(String[] args) {
        TestReadAndWriteLock2 t = new TestReadAndWriteLock2();
//        t.m1();
        t.m2();
    }

    /**
     * 读些锁降级：写锁可以降级为读锁
     */
    public void m1() {
        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
        ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();

        //锁降级
        //1.获取写锁
        writeLock.lock();
        System.out.println("write");
        //2.获取读锁
        readLock.lock();
        System.out.println("read");
        //3.释放写锁
        writeLock.unlock();
        //4.释放读锁
        readLock.unlock();
    }

    /**
     * 读些锁降级：读锁可以降级为写锁（本来这句话就不对，肯定时读锁级别低，写锁级别高。就算能变，那也应该叫升级）
     */
    public void m2() {
        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
        ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();

        //锁降级
        //2.获取读锁
        readLock.lock();
        System.out.println("read");
        //1.获取写锁
        writeLock.lock();
        System.out.println("write");

        //3.释放写锁
        writeLock.unlock();
        //4.释放读锁
        readLock.unlock();
    }
}
